<%
local model = luci.sys.exec("cat /proc/xiaoqiang/model")
%>
    <%include("web/inc/head")%>
        <title>
            <%:小米路由器%>
        </title>
        <meta name="viewport" content="width=1200">
        <link href="<%=resource%>/web/css/bc.css?v=<%=ver%>" rel="stylesheet">
        <link href="<%=resource%>/web/css/layout.css?v=<%=ver%>" rel="stylesheet">
        <link href="<%=resource%>/web/luci/css/misstar.css?v=<%=ver%>" rel="stylesheet">
        <link href="<%=resource%>/web/luci/css/font-awesome/css/font-awesome.min.css" rel="stylesheet">
        </head>

        <body>
            <div id="doc">
                <%
                    local XQSysUtil = require "xiaoqiang.util.XQSysUtil"
                    local XQTopology = require("xiaoqiang.module.XQTopology")
                    local homeUrl = '/'
                    if XQSysUtil.getInitInfo() then
                        homeUrl = luci.dispatcher.build_url("web", "home")
                    end
                    local XQFunction = require("xiaoqiang.common.XQFunction")
                    local router_name = XQFunction.getRouterName()
                    -- ap model
                    local netMode = 0
                    local mode = XQFunction.getNetMode()
                    if mode == "lanapmode" then
                        netMode = 2
                    elseif mode == "wifiapmode" then
                        netMode = 1
                    end
                    local hardware = string.lower( XQSysUtil.getHardware() )
                    local features = require("xiaoqiang.XQFeatures").FEATURES
                    local usbIsSupport = features["hardware"]["usb"]
                    local showTopoLink = 0
                    local topo = XQTopology.topologicalGraph()
                    local leafs = topo["leafs"]
                    if leafs and #leafs > 0 then
                        showTopoLink = 1
                    end
                
                %>
                    <noscript>
                <div class="noscript"><%:你的浏览器禁止了Javascript功能，会造成无法使用系统进行路由器管理，请开启。%></div>
                </noscript>
                    <script>
                        var GLOBALHEADER = true;
                    </script>
                    <div id="hd">
                        <div class="inner">
                            <div class="mod-head clearfix">
                                <h1 id="logo"><a href="<%=homeUrl%>"><img src="<%=resource%>/web/img/logo.png?v=<%=ver%>" alt="<%:小米路由器%>"></a></h1>
                                <div id="nav">
                                    <%if netMode == 0 then%>
                                        <ul>
                                            <li <%if string.find(REQUEST_URI, "/home") then%>class="active"
                                                <%end%>>
                                                    <a href="<%=luci.dispatcher.build_url("web", "home")%>">
                                                        <%:路由状态%>
                                                    </a>
                                            </li>
                                            <%if usbIsSupport == '1' then%>
                                                <li <%if string.find(REQUEST_URI, "/store") then%>class="active"
                                                    <%end%>>
                                                        <a href="<%=luci.dispatcher.build_url("web", "store")%>">
                                                            <%:存储状态%>
                                                        </a>
                                                </li>
                                                <%end%>
                                                    <li <%if string.find(REQUEST_URI, "/setting") then%>class="active"
                                                        <%end%>>
                                                            <a href="<%=luci.dispatcher.build_url("web", "setting", "wifi")%>">
                                                                <%:常用设置%>
                                                            </a>
                                                    </li>
                                                    <li <%if string.find(REQUEST_URI, "/prosetting") then%>class="active"
                                                        <%end%>>
                                                            <a href="<%=luci.dispatcher.build_url("web","prosetting","qos")%>">
                                                                <%:高级设置%>
                                                            </a>
                                                    </li>
                                                    <li <%if string.find(REQUEST_URI, "/misstar") then%>class="active"
                                                        <%end%>>
                                                            <a href="<%=luci.dispatcher.build_url("web","misstar","index")%>">
                                                                <%:MT工具箱%>
                                                            </a>
                                                    </li>
                                        </ul>
                                        <%else%>
                                            <ul>
                                                <li <%if string.find(REQUEST_URI, "/home") then%>class="active"
                                                    <%end%>>
                                                        <a href="<%=luci.dispatcher.build_url("web", "home")%>">
                                                            <%:中继状态%>
                                                        </a>
                                                </li>
                                                <li <%if string.find(REQUEST_URI, "/apsetting") then%>class="active"
                                                    <%end%>>
                                                        <a href="<%=luci.dispatcher.build_url("web", "apsetting", "wifi")%>">
                                                            <%:中继设置%>
                                                        </a>
                                                </li>
                                                <li <%if string.find(REQUEST_URI, "/misstar") then%>class="active"
                                                    <%end%>>
                                                        <a href="<%=luci.dispatcher.build_url("web","misstar","index")%>">
                                                            <%:MT工具箱%>
                                                        </a>
                                                </li>
                                            </ul>
                                            <%end%>
                                </div>
                                <div id="userbar">
                                    <%if (showTopoLink==1) then%>
                                        <span class="goto-topo"><a href="http://miwifi.com/" target="_blank"><%:查看完整网络%></a></span>
                                        <%end%>
                                            <span id="sysmenu" class="name s-dropdown"><%=router_name%></span>
                                            <span id="sysnotice" class="ico-notice"></span>
                                </div>
                            </div>

                            <div class="mod-set-nav mod-set-nav-pro">
                                <ul class="clearfix li-6">
                                    <li class="active"><a href="<%=luci.dispatcher.build_url("web", "misstar", "index")%>">
                                        <i class="ico ico-6"></i>
                                        <span>已安装插件</span>
                                    </a>
                                    </li>
                                    <li>
                                        <a href="<%=luci.dispatcher.build_url("web", "misstar", "add")%>">
                                        <i class="ico ico-8"></i>
                                        <span>插件管理</span>
                                    </a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <div id="bd">
                        <div class="mod-set">
                            <div class="hd">
                                <h3>已安装插件</h3>
                            </div>
                            <div id="app-list" class="wrap"></div>

                        </div>
                    </div>
                    <%include( "web/inc/footer")%>
            </div>
            
            <%
            local ver = require("xiaoqiang.XQVersion").webVersion
            local XQSysUtil = require "xiaoqiang.util.XQSysUtil"
            local remote_addr = luci.http.getenv("REMOTE_ADDR")
            local mac = luci.sys.net.ip4mac(remote_addr)
            local romChannel = XQSysUtil.getChannel()
            local romVersion = XQSysUtil.getRomVersion()
        
            local uci = require("luci.model.uci").cursor()
            local hardwareModel = tostring(uci:get("misc", "hardware", "model"))
            local features = require("xiaoqiang.XQFeatures").FEATURES
            local json = require("luci.json")
        
            local deviceId = tostring(uci:get("messaging", "deviceInfo", "DEVICE_ID"))
        
            local hardware = string.lower( XQSysUtil.getHardware() )
            local color = XQSysUtil.getColor()
            local routerSrc = resource.."/web/img/topograph/".."router_"..hardware.."_".. color..".png"
        
            local XQFunction = require "xiaoqiang.common.XQFunction"
            local netmod = XQFunction.getNetModeType()
        %>
                        <!--[if lt IE 7]>
        <script>
        try{ document.execCommand("BackgroundImageCache",false,true);} catch(e){}
        </script>
        <![endif]-->
                        <div class="mask-menu" id="maskMenu" style="position:fixed;left:0;top:0; width:100%; height:100%; z-index:2; display:none;"></div>
                        <div id="dropmenu" class="dropmenu" style="z-index:3; display:none;">
                            <ul>
                                <li>
                                    <a href="#" id="toRename">
                                        <%:修改路由器名称%>
                                    </a>
                                </li>
                                <%if netmod == 0 then%>
                                    <li>
                                        <a href="<%=luci.dispatcher.build_url("web","setting","upgrade")%>">
                                            <%:系统升级%>
                                        </a>
                                    </li>
                                    <%else%>
                                        <li>
                                            <a href="<%=luci.dispatcher.build_url("web","apsetting","upgrade")%>">
                                                <%:系统升级%>
                                            </a>
                                        </li>
                                        <%end%>
                                            <li>
                                                <a href="#" id="toDownloadClient">
                                                    <%:下载客户端%>
                                                </a>
                                            </li>
                                            <li>
                                                <a href="#" id="toReboot">
                                                    <%:重启%>
                                                </a>
                                            </li>
                                            <%if features["system"]["shutdown"] == '1' then%>
                                                <li>
                                                    <a href="#" id="toShutdown">
                                                        <%:关机%>
                                                    </a>
                                                </li>
                                                <%end%>
                                                    <li class="last">
                                                        <a href="<%=luci.dispatcher.build_url("web","logout")%>">
                                                            <%:注销%>
                                                        </a>
                                                    </li>
                            </ul>
                        </div>
                        <div id="noticebar" class="noticebar" style="z-index:3; display:none;">
                            <i class="ico-arrow"></i>
                            <div class="content"></div>
                        </div>
                        <%include("web/inc/i18n.js")%>
                            <script src="/js/jquery-1.8.3.js?v=<%=ver%>"></script>
                            <script src="/js/qwrap.js?v=<%=ver%>"></script>
                            <script src="/js/common.js?v=<%=ver%>"></script>
                            <script src="/js/raphael.js?v=<%=ver%>"></script>
                            <script src="/js/crypto-js/rollups/sha1.js?v=<%=ver%>"></script>
                            <script src="/js/crypto-js/rollups/aes.js?v=<%=ver%>"></script>
                            <script src="/js/valid.js?v=<%=ver%>"></script>
                            <script src="<%=resource%>/web/js/selectbeautify.js?v=<%=ver%>"></script>
                            <script src="<%=resource%>/web/js/jquery.dialog.js?v=<%=ver%>"></script>
                            <script src="<%=resource%>/web/js/jquery.cookie.js?v=<%=ver%>"></script>
                            <script>
                                (function() {
                                    var G_FEATURES = $.parseJSON('<%=json.encode(features)%>');
                                    window['G_FEATURES'] = G_FEATURES;
                                }())
                            </script>
                            <%include("web/inc/reboot.js")%>
                                <script type="text/tmpl" id="tplrename">
                                    <div class="mod-rename-dlg">
                                        <p class="img"><img src="<%=routerSrc %>"></p>
                                        <div class="form-rename">
                                            <form action="#" class="form" id="routerNameEdit">
                                                <div class="form-item">
                                                    <label class="k"><%:路由器名称%></label>
                                                    <span class="v">
                            <input type="text" name="routername" id="routername" class="ipt-text" autocomplete="off" datatype="bytetext" maxlength="24" reqMsg="<%:路由器名称%>" value="{$name}">
                        </span>
                                                    <em class="t"></em>
                                                </div>
                                                <div class="form-item">
                                                    <label class="k"><%:位置%></label>
                                                    <span class="v">
                            <input type="text" name="locale" id="locale" class="ipt-text" autocomplete="off" datatype="bytetext" maxlength="24" reqMsg="<%:路由器位置%>" value="{$locale}">
                        </span>
                                                    <em class="t"></em>
                                                </div>
                                                <div class="form-contral">
                                                    <button type="submit" class="btn btn-primary btn-l"><span><%:保存%></span></button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </script>
                                <script type="text/tmpl" id="tplshutdown">
                                    <div class="mod-reboot-dlg">
                                        <p class="img"><img src="<%=resource%>/web/img/ico_shutdown.png"></p>
                                        <p class="text">
                                            <%:关闭路由器将断开其他设备的数据访问和网络连接，之后便可以安全的断开电源。（再次启动需要手工连接电源）%>
                                        </p>
                                        <button id="shutdownAction" type="button" class="btn btn-primary btn-l"><span><%:关闭路由器%></span></button>
                                    </div>
                                </script>
                                <script type="text/tmpl" id="tplreboot">
                                    <div class="mod-shutdown-dlg">
                                        <p class="img"><img src="<%=resource%>/web/img/ico_reboot.png"></p>
                                        <p class="text">
                                            <%:路由器重启需要等待十几秒或更多时间，重启过程中将会断开网络连接，稍后将自动重新连接网络。%>
                                        </p>
                                        <button type="button" id="rebootAction" class="btn btn-primary btn-l"><span><%:重启路由器%></span></button>
                                    </div>
                                </script>
                                <script type="text/tmpl" id="tpldownloadclient">
                                    <div class="mod-downloadclient-dlg">
                                        <table>
                                            <tr>
                                                <td>
                                                    <i class="ico-down-client ico-down-pc"></i>
                                                    <a href="http://bigota.miwifi.com/xiaoqiang/client/xqpc_client.exe">
                                                        <%:PC客户端%>
                                                    </a>
                                                </td>
                                                <td class="c1"></td>
                                                <td class="c2"></td>
                                                <td>
                                                    <i class="ico-down-client ico-down-mac"></i>
                                                    <a href="http://bigota.miwifi.com/xiaoqiang/client/xqmac_client.dmg">
                                                        <%:MAC客户端%>
                                                    </a>
                                                </td>
                                            </tr>
                                            <tr class="last">
                                                <td>
                                                    <i class="ico-down-client ico-down-andriod"></i>
                                                    <%if romChannel == "release" then%>
                                                        <a href="http://bigota.miwifi.com/xiaoqiang/client/xqapp.apk">
                                                            <%:Android客户端%>
                                                        </a>
                                                        <img class="onlineimg" src-local="<%=resource%>/web/img/2dcode.png" src="http://www1.miwifi.com/statics/img/wf_2dcode_an_dl.png">
                                                        <%else%>
                                                            <a href="http://bigota.miwifi.com/xiaoqiang/client/xqapp_dev.apk">
                                                                <%:Android客户端%>
                                                            </a>
                                                            <img class="onlineimg" src-local="<%=resource%>/web/img/2dcode.png" src="http://www1.miwifi.com/statics/img/wf_2dcode_an_dl_dev.png">
                                                            <%end%>
                                                </td>
                                                <td class="c1"></td>
                                                <td class="c2"></td>
                                                <td>
                                                    <i class="ico-down-client ico-down-iphone"></i>
                                                    <a href="https://itunes.apple.com/cn/app/id859962702?mt=8&ls=1">
                                                        <%:iPhone客户端%>
                                                    </a>
                                                    <img class="onlineimg" src-local="<%=resource%>/web/img/2dcode.png" src="http://www1.miwifi.com/statics/img/wf_2dcode_ios_dl.png">
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                </script>
                                <script>
                                    var DEBUG = false;
                                    if (!window.console || DEBUG == false) {
                                        window.console = {
                                            log: function() {}
                                        };
                                    }
        
                                    var Encrypt = {
                                        key: 'a2ffa5c9be07488bbb04a3a47d3c5f6a',
                                        iv: '64175472480004614961023454661220',
                                        nonce: null,
                                        init: function() {
                                            var nonce = this.nonceCreat();
                                            this.nonce = nonce;
                                            return this.nonce;
                                        },
                                        nonceCreat: function() {
                                            var type = 0;
                                            var deviceId = '<%=mac%>';
                                            var time = Math.floor(new Date().getTime() / 1000);
                                            var random = Math.floor(Math.random() * 10000);
                                            return [type, deviceId, time, random].join('_');
                                        },
                                        oldPwd: function(pwd) {
                                            return CryptoJS.SHA1(this.nonce + CryptoJS.SHA1(pwd + this.key).toString()).toString();
                                        },
                                        newPwd: function(pwd, newpwd) {
                                            var key = CryptoJS.SHA1(pwd + this.key).toString();
                                            key = CryptoJS.enc.Hex.parse(key).toString();
                                            key = key.substr(0, 32);
                                            key = CryptoJS.enc.Hex.parse(key);
                                            var password = CryptoJS.SHA1(newpwd + this.key).toString();
                                            var iv = CryptoJS.enc.Hex.parse(this.iv);
                                            var aes = CryptoJS.AES.encrypt(
                                                password,
                                                key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 }
                                            ).toString();
                                            return aes;
                                        }
                                    };
        
                                    var pingRouter = function(on, off, ip) {
                                        var online = on || function() {},
                                            offline = off || function() {},
                                            host = ip || location.host,
                                            imgUrl = 'http://' + host + '/xiaoqiang/web/img/logo.png',
                                            time = 5000,
                                            timecounter = 0,
                                            img = null,
                                            wait = function() {
                                                console.log('pingRouter:wait');
                                                offline();
                                            },
                                            done = function() {
                                                console.log('pingRouter:done');
                                                window.clearInterval(timer);
                                                online();
                                            },
                                            loadImg = function(onload, onerror) {
                                                img = new Image();
                                                img.onload = onload;
                                                img.onerror = onerror;
                                                img.src = imgUrl + '?' + (+new Date());
                                            },
                                            timer = window.setInterval(function() {
        
                                                if ('onLine' in navigator) {
                                                    if (navigator.onLine) {
                                                        loadImg(
                                                            function() {
                                                                done();
                                                            },
                                                            function() {
                                                                wait();
                                                            }
                                                        );
                                                    } else {
                                                        wait();
                                                    }
                                                } else {
                                                    loadImg(function() {
                                                        done();
                                                    }, function() {
                                                        wait();
                                                    });
                                                }
                                            }, time);
                                    };
        
                                    var rebootWait = function(opt) {
                                        var action = opt.action,
                                            ip = opt.lanIp || window.location.host,
                                            refresh = opt.refresh || false,
                                            tStart = (+new Date()),
                                            tUse,
                                            dlgRebootWait = $.loadingDialog({
                                                title: '<%:重启中...%>',
                                                content: '<%:操作生效，等待设备重启...%>'
                                            }),
                                            online = function() {
                                                dlgRebootWait.content('<%:操作生效,重启成功！%>');
                                                dlgRebootWait.time(3 * 1000);
                                                if (refresh) {
                                                    window.setTimeout('window.top.location.href="http://' + ip + '";', 3000);
                                                }
                                            },
                                            offline = function() {
                                                tUse = Math.round(((+new Date()) - tStart) / 1000);
                                                if (tUse > 150) {
                                                    dlgRebootWait.content('<%:自动连接路由器失败，请检查无线或者网线是否连接正确。%>');
                                                    return;
                                                }
                                                dlgRebootWait.content(action + '<%:, 等待自动跳转... 用时{$time}秒%>'.tmpl({ time: tUse }));
                                            };
        
                                        window.setTimeout(function() {
                                            pingRouter(online, offline, ip);
                                        }, 1000 * 60);
                                    };
        
                                    (function($) {
        
                                        function formInit(container) {
                                            var clsInput = 'form-item form-item-input',
                                                clsEmpty = 'form-item form-item-empty',
                                                clsDisabled = 'form-item-disabled',
                                                clsError = 'form-item-err',
                                                clsPassword = 'form-item-pwd';
        
                                            container = container || 'body';
                                            $(container).find('.form-item input').each(function() {
                                                var me = this,
                                                    $me = $(me),
                                                    parent = $(me.parentNode.parentNode),
                                                    label = parent.find('.k'),
                                                    offsetX = $me.position().left;
                                                if (!(this.type == 'text' || this.type == 'password')) {
                                                    return;
                                                }
                                                // some input do not need init
                                                if ($me.hasClass('no-init')) {
                                                    return;
                                                }
                                                if (me.value !== '') {
                                                    parent[0].className = clsInput;
                                                } else {
                                                    parent[0].className = clsEmpty;
                                                    if (offsetX > 0) {
                                                        label.css({ 'left': offsetX + 10 });
                                                    }
                                                }
                                                if (me.disabled) {
                                                    parent.addClass(clsDisabled);
                                                }
                                                if ($me.attr('data-type') === 'password') {
                                                    parent.addClass(clsPassword);
                                                    parent.append('<i class="bt-showpwd bt-showpwd-off"></i>');
                                                }
        
                                                label.on('click', function(e) {
                                                    try {
                                                        me.focus();
                                                    } catch (ex) {}
                                                });
        
                                            });
                                            var focusHandler = function() {
                                                if (!(this.type == 'text' || this.type == 'password')) {
                                                    return;
                                                }
                                                var me = $(this),
                                                    parent = $(this.parentNode.parentNode),
                                                    label = parent.find('.k'),
                                                    t = parent.find('.t'),
                                                    classname;
                                                if (me.hasClass('no-init')) {
                                                    return;
                                                }
                                                if (parent.hasClass(clsPassword)) {
                                                    classname = clsInput + ' ' + clsPassword;
                                                } else {
                                                    classname = clsInput;
                                                }
                                                if (parent.hasClass(clsError)) {
                                                    t.hide();
                                                }
                                                label.css({ 'left': 'auto' });
                                                label.hide();
                                                parent[0].className = classname;
                                            };
                                            var blurHandler = function() {
                                                var me = this,
                                                    $me = $(me),
                                                    parent = $(me.parentNode.parentNode),
                                                    classname,
                                                    label = parent.find('.k'),
                                                    offsetX = $me.position().left;
                                                if (!(this.type == 'text' || this.type == 'password')) {
                                                    return;
                                                }
                                                if ($(this).hasClass('no-init')) {
                                                    return;
                                                }
                                                label.show();
                                                if (me.value == '') {
                                                    if (parent.hasClass(clsPassword)) {
                                                        classname = clsEmpty + ' ' + clsPassword;
                                                    } else {
                                                        classname = clsEmpty;
                                                    }
                                                    if (offsetX > 0) {
                                                        label.css({ 'left': offsetX + 10 });
                                                    } else {
                                                        label.css({ 'left': 12 });
                                                    }
                                                    parent[0].className = classname;
                                                }
                                            };
                                            var addInputEvent = function() {
                                                $(container).find('.form-item input')
                                                    .on('focus', focusHandler)
                                                    .on('blur', blurHandler);
                                            };
        
                                            var delInputEvent = function() {
                                                $(container).find('.form-item input').off('focus', focusHandler);
                                                $(container).find('.form-item input').off('blur', blurHandler);
                                            };
                                            // del password event
                                            $('body').undelegate('.bt-showpwd', 'click');
                                            $('body').delegate('.bt-showpwd', 'click', function(e) {
                                                console.log('showpwd');
                                                var me = this,
                                                    meclass = 'bt-showpwd',
                                                    formItem = $(this).closest('.form-item'),
                                                    input = formItem.find('input'),
                                                    inputValue = input.val(),
                                                    inputWrap = formItem.find('.v'),
                                                    newinput = '',
                                                    inputHTML = inputWrap.html();
        
                                                if (input.attr('type') == 'password') {
                                                    newinput = inputHTML.replace(/type\s*=\s*('|")?password('|")?/ig, 'type="text"');
                                                    inputWrap.html(newinput).find('input')[0].value = inputValue;
                                                    me.className = meclass + ' bt-showpwd-on';
                                                } else {
                                                    newinput = inputHTML.replace(/type\s*=\s*('|")?text('|")?/ig, 'type="password"');
                                                    inputWrap.html(newinput).find('input')[0].value = inputValue;
                                                    me.className = meclass + ' bt-showpwd-off';
                                                }
        
                                                setTimeout(function() {
                                                    delInputEvent();
                                                    addInputEvent();
                                                }, 0);
                                            });
        
                                            addInputEvent();
                                        }
        
                                        $.formInit = formInit;
        
                                    })(jQuery);
        
                                    /**
                                     * byte format
                                     */
                                    function byteFormat(number, precision, isarray) {
                                        var val,
                                            label,
                                            ret;
                                        precision = precision || 100,
                                            isarray = isarray || false;
                                        if (number > 1024 * 1024 * 1024) {
                                            val = Math.floor(number / 1024 / 1024 / 1024 * precision) / precision;
                                            label = 'GB';
                                        } else if (number > 1024 * 1024 && number < 1024 * 1024 * 1024) {
                                            val = Math.floor(number / 1024 / 1024 * precision) / precision;
                                            label = 'MB';
                                        } else {
                                            val = Math.floor(number / 1024 * precision) / precision;
                                            label = 'KB';
                                        }
        
                                        if (isarray) {
                                            ret = [val, label];
                                        } else {
                                            ret = val + label;
                                        }
        
                                        return ret;
                                    }
        
        
                                    function secondToHour(time) {
                                        var pint = function(num) {
                                                return parseInt(num, 10);
                                            },
                                            hour = pint(time / 3600.0),
                                            minute = pint((parseFloat(time / 3600.0) - hour) * 60),
                                            second = pint(time) - hour * 3600 - minute * 60,
                                            format = hour + '<%:小时%>' + minute + '<%:分%>' + second + '<%:秒%>';
                                        return format;
                                    }
        
                                    function secondToDate(second) {
                                        var time = parseFloat(second),
                                            pint = function(num) {
                                                return parseInt(num, 10);
                                            },
                                            day;
                                        if (time !== null && time !== "") {
                                            if (time > 60 && time < 60 * 60) {
                                                time = pint(time / 60.0) + '<%:分%>' + pint((parseFloat(time / 60.0) - pint(time / 60.0, 10)) * 60) + '<%:秒%>';
                                            } else if (time >= 60 * 60 && time < 60 * 60 * 24) {
                                                time = secondToHour(time);
                                            } else if (time >= 24 * 60 * 60) {
                                                day = pint(time / (3600.0 * 24));
                                                time = time - (day * 3600 * 24);
                                                time = day + '<%:天 %>' + secondToHour(time);
                                            } else {
                                                time = pint(time) + '<%:秒%>';
                                            }
                                        }
                                        return time;
                                    }
        
                                    (function($) {
                                        function pint(num) {
                                            return parseInt(num, 10);
                                        }
        
                                        function secondToHour(time) {
                                            var hour = pint(time / 3600.0),
                                                minute = pint((parseFloat(time / 3600.0) - hour) * 60),
                                                second = pint(time) - hour * 3600 - minute * 60,
                                                format = hour + '<%:小时%>' + minute + '<%:分%>' + second + '<%:秒%>';
                                            return format;
                                        }
        
                                        function secondToDate(second) {
                                            var time = parseFloat(second),
                                                day;
                                            if (time !== null && time !== "") {
                                                if (time > 60 && time < 60 * 60) {
                                                    time = pint(time / 60.0) + '<%:分%>' + pint((parseFloat(time / 60.0) - pint(time / 60.0, 10)) * 60) + '<%:秒%>';
                                                } else if (time >= 60 * 60 && time < 60 * 60 * 24) {
                                                    time = secondToHour(time);
                                                } else if (time >= 24 * 60 * 60) {
                                                    day = pint(time / (3600.0 * 24));
                                                    time = time - (day * 3600 * 24);
                                                    time = day + '<%:天%>' + secondToHour(time);
                                                } else {
                                                    time = pint(time) + '<%:秒%>';
                                                }
                                            }
                                            return time;
                                        }
        
                                        function secondToDate2(second) {
                                            var time = parseFloat(second),
                                                num = 0,
                                                unit = '<%:天%>';
                                            console.log(second, time);
                                            if (!isNaN(time)) {
                                                if (time > 60 && time < 60 * 60) {
                                                    num = Math.floor(time / 60.0);
                                                    unit = '<%:分钟%>';
                                                } else if (time >= 60 * 60 && time < 60 * 60 * 24) {
                                                    num = Math.floor(time / 3600.0);
                                                    unit = '<%:小时%>'
                                                } else if (time >= 24 * 60 * 60) {
                                                    num = Math.floor(time / (3600.0 * 24));
                                                    unit = '<%:天%>';
                                                } else {
                                                    num = Math.floor(time);
                                                    unit = '<%:秒%>';
                                                }
                                            }
                                            return {
                                                num: num,
                                                unit: unit
                                            };
                                        }
        
                                        $.secondToHour = secondToHour;
                                        $.secondToDate = secondToDate;
                                        $.secondToDate2 = secondToDate2;
                                    })(jQuery);
        
        
                                    $(document).ajaxSuccess(function(event, xhr, settings) {
                                        var rsp = xhr.responseText;
                                        rsp = $.parseJSON(rsp);
                                        // console.log(event, xhr, settings);
                                        var ignore = [
                                            'api\/xqsystem\/login',
                                            'api\/xqsystem\/upgrade_rom'
                                        ];
                                        for (var i = 0; i < ignore.length; i++) {
                                            var ignoreTest = new RegExp(ignore[i]);
                                            // console.log( ignoreTest );
                                            if (ignoreTest.test(settings.url)) {
                                                return;
                                            }
                                        }
                                        if (rsp.code === 401 || rsp.code === 403) {
                                            document.location.href = 'http://' + location.host;
                                        }
                                    });
        
                                    $.sub('wait', function(evt, data) {
                                        var selector = data.id;
                                        if (!$.waitStatus) {
                                            $.waitStatus = {};
                                        }
                                        $.waitStatus[selector] = $(selector).text();
                                        $(selector).addClass('btn-primary-disabled').prop('disabled', true).find('span').text('<%:处理中%>...');
                                    });
        
                                    $.sub('done', function(evt, data) {
                                        var selector = data.id,
                                            text = $.waitStatus[selector];
                                        $(selector).removeClass('btn-primary-disabled').prop('disabled', false).find('span').text(text);
                                    });
        
                                    $.sub('loading:start', function() {
                                        var isLoading = $('html').hasClass('isloading');
                                        if (isLoading) {
                                            return;
                                        }
                                        var tplMask = '<div id="panel-loading-mask" class="panel-mask" style="position:fixed;left:0;top:0;style:none;"></div>',
                                            tplLoading = '' +
                                            '<div id="panel-loading" class="panel-loading" style="style:none;">' +
                                            '<img src="/img/loading2.gif">' +
                                            '</div>',
                                            $mask = $(tplMask),
                                            $loading = $(tplLoading),
                                            zIndex = 10000;
                                        $mask.css({
                                            'z-index': zIndex,
                                            width: $(window).width() + 'px',
                                            height: $(window).height() + 'px'
                                        });
                                        $loading.css({ 'z-index': zIndex + 1 });
                                        $mask.appendTo(document.body).show();
                                        $loading.appendTo(document.body).show();
                                        $('html').addClass('isloading');
                                    });
        
                                    $.sub('loading:stop', function() {
                                        $('html').removeClass('isloading');
                                        $('#panel-loading, #panel-loading-mask').remove();
                                    });
        
                                    // dialog block loading
                                    (function($) {
                                        $.loadingDialog = function(config) {
                                            var mix = ObjectH.mix,
                                                _config = config || {
                                                    title: '',
                                                    content: ''
                                                },
                                                conf = mix(_config, {
                                                    width: 390,
                                                    padding: '25px 30px',
                                                    title: config.title,
                                                    content: '<p style="padding-bottom:30px;">{$content}</p><div class="loading-bar"></div>'.tmpl({ content: config.content }),
                                                    cancel: false
                                                }, true),
                                                dialog = $.dialog(conf);
        
                                            var oldcontent = dialog.content;
                                            dialog.content = function(cont) {
                                                var _cont = '<p style="padding-bottom:30px;">{$content}</p><div class="loading-bar"></div>'.tmpl({ content: cont });
                                                return oldcontent.call(dialog, _cont);
                                            };
                                            return dialog;
                                        }
                                    })(jQuery);
        
                                    // dialog alert
                                    (function($) {
                                        $.alert = function(content, ok) {
                                            ok = ok || function() {};
                                            return $.dialog({
                                                width: 390,
                                                padding: '25px 30px',
                                                title: '<%:提示信息%>',
                                                content: content,
                                                ok: ok,
                                                cancel: false
                                            });
                                        }
                                    })(jQuery);
        
                                    // dialog confirm
                                    (function($) {
                                        $.confirm = function(content, ok, cancel) {
                                            var _cancel = cancel || function() {};
                                            return $.dialog({
                                                width: 390,
                                                padding: '25px 30px',
                                                title: '<%:确认信息%>',
                                                content: content,
                                                ok: ok,
                                                cancel: _cancel,
                                                lock: true
                                            });
                                        }
                                    })(jQuery);
        
                                    // wechat code dialog
                                    $(function() {
                                        $('#wechatcode').click(function(e) {
                                            e.preventDefault();
                                            var $this = $(this),
                                                href = $this.attr('href');
                                            $.dialog({
                                                title: '<%:官方微信%>',
                                                content: '<img width="200" src="' + href + '">',
                                                width: 250,
                                                lock: true
                                            });
                                        });
                                    });
        
        
                                    // set sys language
                                    (function($) {
                                        $.i18nSet = function(el) {
                                            var $lan = $(el),
                                                apiGetLan = '<%=luci.dispatcher.build_url("api", "xqsystem", "get_languages")%>',
                                                apiSetlan = '<%=luci.dispatcher.build_url("api", "xqsystem", "set_language")%>',
                                                dtd = $.Deferred();
        
                                            $.get(apiGetLan, function(rsp) {
                                                var rsp = $.parseJSON(rsp);
                                                var selectContent = [];
                                                if (rsp.code == 0) {
                                                    for (var i = 0; i < rsp.list.length; i++) {
                                                        var item = rsp.list[i],
                                                            selected = item.lang == rsp.lang ? 'selected' : '',
                                                            option = '<option value="' + item.lang + '" ' + selected + '>' + item['name'] + '</option>';
                                                        // clear old conf en item
                                                        // if ( item.lang != 'en') {
                                                        selectContent.push(option);
                                                        // }
                                                    };
                                                    $lan.html(selectContent.join(''));
                                                    dtd.resolve();
                                                }
                                            });
        
                                            $lan.on('change', function(e) {
                                                var el = this,
                                                    val = $(this).val();
                                                $.pub('loading:start');
                                                $.post(apiSetlan, { language: val }, function(rsp) {
                                                    var rsp = $.parseJSON(rsp);
                                                    if (rsp.code == 0) {
                                                        location.reload(1);
                                                    } else {
                                                        $.alert(rsp.msg);
                                                    }
                                                    $.pub('loading:stop');
                                                });
                                            });
        
                                            return dtd.promise();
                                        };
                                    }(jQuery));
        
        
        
                                    // global event
                                    (function($) {
                                        var dlgReboot,
                                            dlgShutdown,
                                            dlgRouterName;
        
                                        function getNotice() {
                                            $.getJSON('<%=luci.dispatcher.build_url("api", "misystem", "messages")%>', function(rsp) {
                                                if (rsp.code == 0) {
                                                    var classname;
                                                    if (rsp.count > 0) {
                                                        classname = 'ico-notice-new';
                                                    } else {
                                                        classname = 'ico-notice';
                                                    }
                                                    $('#sysnotice')[0].className = classname;
                                                    var msgMap = {
                                                        '1': '<p><%:检测到最新版本为{$version}%>，<a href="<%=luci.dispatcher.build_url("web","setting","upgrade")%>"><%:点击此处立即升级%></a>。</p>',
                                                        '3': '<p><%:5G Wi-Fi启动失败，%><a target="_blank" href="http://www.mi.com/service/contact/"><%:请联系小米客服解决%></a></p>',
                                                        '4': '<p><%:检测到与上级路由器存在IP冲突，建议切换到%><a href="<%=luci.dispatcher.build_url("web","setting","wan")%>#netmode"><%:有线中继模式%></a><%:或者%><a href="#" id="ipconflict" data-ip="{$ip}"><%:避让IP冲突%></p>'
                                                    };
                                                    var msgHTML = [];
                                                    for (var i = rsp.messages.length - 1; i >= 0; i--) {
                                                        msgHTML.push(msgMap[rsp.messages[i].type].tmpl(rsp.messages[i].data));
                                                    };
                                                    $('#noticebar .content').html(msgHTML.join(''));
        
                                                    if (rsp.count > 0) {
                                                        $('#sysnotice').trigger('click');
                                                    }
                                                }
                                            });
                                        }
        
                                        function reNameHandler(e) {
                                            e.preventDefault();
                                            $.getJSON('<%=luci.dispatcher.build_url("api", "misystem", "router_name")%>')
                                                .done(function(rsp) {
                                                    if (rsp.code == 0) {
                                                        var html = StringH.tmpl($('#tplrename').html(), {
                                                            locale: StringH.encode4HtmlValue(rsp.locale),
                                                            name: StringH.encode4HtmlValue(rsp.name)
                                                        });
                                                        dlgRouterName = $.dialog({
                                                            width: 390,
                                                            title: '<%:修改路由器名称%>',
                                                            content: html,
                                                            lock: true
                                                        });
                                                        setTimeout(function() {
                                                            $.formInit('.mod-rename-dlg');
                                                            $.selectBeautify({ container: '.mod-rename-dlg' });
                                                        }, 100);
                                                    }
                                                });
                                        }
        
                                        function downloadClientHandler(e) {
                                            e.preventDefault();
                                            $.dialog({
                                                width: 390,
                                                title: '<%:下载客户端%>',
                                                content: $('#tpldownloadclient').html(),
                                                lock: true
                                            });
                                            setTimeout(function() {
                                                $('.onlineimg').each(function() {
                                                    var img = new Image();
                                                    var el = this;
                                                    var remote = el.src;
                                                    var local = $(el).attr('src-local');
                                                    img.onerror = function() {
                                                        el.src = local;
                                                    }
                                                    img.src = remote;
                                                });
                                            }, 100);
                                        }
        
                                        function rebootHandler(e) {
                                            e.preventDefault();
                                            dlgReboot = $.dialog({
                                                width: 390,
                                                title: '<%:重启路由器%>',
                                                content: $('#tplreboot').html(),
                                                lock: true
                                            });
                                        }
        
                                        function shutdownHandler(e) {
                                            e.preventDefault();
                                            dlgShutdown = $.dialog({
                                                width: 390,
                                                title: '<%:路由器关机%>',
                                                content: $('#tplshutdown').html(),
                                                lock: true
                                            });
                                        }
        
                                        function noticeHandler(e) {
                                            e.preventDefault();
                                            var that = this,
                                                $this = $(this),
                                                pos = $('#userbar').position(),
                                                right,
                                                wt = 1160,
                                                wwt = $(window).width(),
                                                $arrow = $('#noticebar .ico-arrow');
                                            if ($this.hasClass('ico-notice-new')) {
                                                // right = wt - pos.left - 20;
                                                $arrow.css({ 'right': '10px' });
                                                $('#noticebar').css({ 'right': (wwt - wt) / 2 });
                                                $('#noticebar').toggle();
                                            }
                                            $('#maskMenu').height($(window).height());
                                            $('#maskMenu').show();
                                        }
        
                                        function sysmenuHandler(e) {
                                            e.preventDefault();
                                            var that = this,
                                                $this = $(this);
                                            if ($this.hasClass('s-dropdown')) {
                                                var ww = $(window).width();
                                                // var rt = (ww - 1160) / 2;
                                                var lt = $this.offset().left + $this.outerWidth() - $('#dropmenu').width();
                                                $('#dropmenu').css({ left: lt });
                                                $('#dropmenu').show();
                                                that.className = 'name s-dropup';
                                            } else {
                                                $('#dropmenu').hide();
                                                that.className = 'name s-dropdown';
                                            }
                                            $('#maskMenu').height($(window).height());
                                            $('#maskMenu').show();
                                        }
        
                                        function maskHandler(e) {
                                            e.preventDefault();
                                            $('#noticebar').hide();
                                            $('#dropmenu').hide();
                                            $('#maskMenu').hide();
                                            $('#sysmenu')[0].className = 'name s-dropdown';
                                        }
        
                                        $(function() {
                                            // notice
                                            $('#sysnotice').click(noticeHandler);
                                            // user dropmenu
                                            $('#sysmenu').click(sysmenuHandler);
                                            // space click
                                            $('#maskMenu').click(maskHandler);
                                            // rename
                                            $('body').delegate('#toRename', 'click', reNameHandler);
                                            // toDownloadClient
                                            $('body').delegate('#toDownloadClient', 'click', downloadClientHandler);
                                            // toReboot
                                            $('body').delegate('#toReboot', 'click', rebootHandler);
                                            // toShutdown
                                            $('body').delegate('#toShutdown', 'click', shutdownHandler);
        
                                            $('body').delegate('#shutdownAction', 'click', function(e) {
                                                e.preventDefault();
                                                dlgShutdown.close();
                                                shutdown_window();
                                            });
        
                                            $('body').delegate('#rebootAction', 'click', function(e) {
                                                e.preventDefault();
                                                dlgReboot.close();
                                                reboot_window();
                                            });
        
                                            $('body').delegate('#routerNameEdit', 'submit', function(e) {
                                                e.preventDefault();
                                                var validator = Valid.checkAll(this);
                                                var routername = $('#routername').val();
                                                var locale = $('#locale').val();
                                                if (validator) {
                                                    $.getJSON('<%=luci.dispatcher.build_url("api","misystem","set_router_name")%>', {
                                                        name: routername,
                                                        locale: locale
                                                    }).done(function(rsp) {
                                                        if (rsp.code == 0) {
                                                            location.reload(1);
                                                        } else {
                                                            $.alert(rsp.msg)
                                                        }
                                                    });
                                                }
                                            });
        
                                            $('body').delegate('#ipconflict', 'click', function(e) {
                                                e.preventDefault();
                                                var api = '<%=luci.dispatcher.build_url("api", "misystem", "r_ip_conflict")%>',
                                                    ip = $(this).attr('data-ip');
                                                $.dialog({
                                                    title: '<%:避让IP冲突%>',
                                                    content: '<%:执行此操作，局域网IP将会变更为%>' + ip + '<br>' + '<%:该过程无线网络会重启，将出现短暂掉线。%>',
                                                    lock: true,
                                                    ok: function() {
                                                        $.post(api, function(rsp) {
                                                            rsp = $.parseJSON(rsp);
                                                            if (rsp.code !== 0) {
                                                                alert(rsp.msg);
                                                            }
                                                        });
                                                    },
                                                    cancel: function() {}
                                                });
                                            });
        
                                            // user logined and has global header get notice
                                            if (typeof(GLOBALHEADER) !== 'undefined' && GLOBALHEADER === true) {
                                                getNotice();
                                            }
                                        });
                                    })(jQuery);
                                </script>
                                <script src="/js/miwifi-monitor.js"></script>
                                <script>
                                    // 流量统计
                                </script>


                <script type="text/javascript" src="<%=resource%>/web/luci/layer-pc/layer.js"></script>
                <script type="tmpl/html" id="tplapplist">
                    {if($applist.length > 0)} {for(var i=0; i
                    < $applist.length; i++)} <div class="box site-demo-active" data-type="{$applist[i].href}" onclick="openLayer('{$applist[i].href}')">
                        <img src="<%=resource%>/web/luci/img/{$applist[i].icon}.png">
                        <p>{$applist[i].title}</p>
                        </div>
                        {/for} {else}
                        <tr>
                            <td colspan="2" class="center">没有设置信息</td>
                        </tr>
                        {/if}
                </script>

                <script type="tmpl/html" id="tmpsysinfo">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">版本：</label>
                            <div class="layui-form-mid">{$version}</div>
                            <div class="box site-demo-active" style="top: 15px;float: left;">
                                <a style="display: none;float: left;" id="upgrade" href="javascript:;" class="layui-btn layui-btn-normal  layui-btn-small" onclick="upgrade();">升级</a>
                            </div>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">QQ群：</label>
                            <div class="layui-form-mid">
                                <a target="_blank" href="http://shang.qq.com/wpa/qunwpa?idkey=4d98dcf63441cd34accd7f38c04657ab05895620976efd3cf86de551b5be16ea"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png" alt="小米路由插件交流" title="小米路由插件交流"></a>
                                <a target="_blank" href="http://shang.qq.com/wpa/qunwpa?idkey=dff6dc69cd2e3f9e859b566e448baa98d1add033691a6d35d57d3175e727fb0d"><img border="0" src="http://pub.idqqimg.com/wpa/images/group.png" alt="小米路由插件交流" title="小米路由插件交流"></a>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">安装统计：</label>
                            <div class="layui-form-mid">您是第<b>{$counter}</b>位安装本工具箱用户，共<b>{$countersum}</b>位用户安装了本工具箱，安装应用<b>{$appcounter}</b>次。<a href="javascript:;" onclick="uninstall();" style="color: red;"><b>卸载工具箱</b></a></div>
                        </div>
                    </div>
                </script>

                <script>
                    function initMT() {
                        var tpl = $('#tplapplist').html();
                        tpldata = [];
                        var navs = $.getJSON('/xiaoqiang/web/luci/js/nav.json', {}, function(navs) {
                            if (navs[0].children.length > 0) {
                                var list = {};
                                var icon;
                                $.pub('loading:start');
                                $.ajax({
                                    url: "http://www.misstar.com/tools/appstore/<%=model%>/applist.php",
                                    jsonp: 'callback',
                                    dataType: 'jsonp',
                                    data: '',
                                    timeout: 500,
                                    success: function(rsp) {
                                        if (rsp.code == 0) {
                                            list = rsp.applist;
                                            for (var i = 0; i < navs[0].children.length; i++) {
                                                for (var j = 0; j < list.length; j++) {
                                                    icon = navs[0].children[i].href;
                                                    if (navs[0].children[i].href == list[j].href) {
                                                        if (navs[0].children[i].version < list[j].version) {
                                                            icon = navs[0].children[i].href + "_ua";
                                                        }
                                                        break;
                                                    }
                                                }
                                                var item = {
                                                    title: navs[0].children[i].title,
                                                    href: navs[0].children[i].href,
                                                    icon: icon
                                                }
                                                tpldata.push(item);
                                            }
                                            $('#app-list').html(tpl.tmpl({
                                                applist: tpldata
                                            }));
                                        }
                                    },
                                    error: function(e) {

                                        for (var i = 0; i < navs[0].children.length; i++) {
                                            icon = navs[0].children[i].href;
                                            var item = {
                                                title: navs[0].children[i].title,
                                                href: navs[0].children[i].href,
                                                icon: icon
                                            }
                                            tpldata.push(item);
                                        }
                                        $('#app-list').html(tpl.tmpl({
                                            applist: tpldata
                                        }));

                                    },
                                    complete: function(XMLHttpRequest, textStatus) {
                                        $.pub('loading:stop');
                                    }
                                });

                            }

                            return navs;
                        });

                        xhr = $.getJSON('<%=luci.dispatcher.build_url("api", "misstar", "get_status")%>', {}, function(rsp) {
                            if (rsp.code == 0) {
                                var tpl = $('#tmpsysinfo').html();
                                var tpldata = {
                                    version: '',
                                    counter: '',
                                    cputmp: '',
                                    boardtmp: '',
                                    fanspeed: '',
                                    countersum: '1',
                                    appcounter: '1'
                                };
                                tpldata.version = rsp.version;
                                tpldata.counter = rsp.counter;
                                tpldata.cputmp = rsp.cputmp;
                                tpldata.boardtmp = rsp.boardtmp;
                                tpldata.fanspeed = rsp.fanspeed;


                                setTimeout(function() {
                                    $('#sysinfo').html(tpl.tmpl(tpldata));
                                    version = rsp.version;
                                    $.ajax({
                                        url: "http://www.misstar.com/tools/appstore/<%=model%>/misstar.php",
                                        jsonp: 'callback',
                                        dataType: 'jsonp',
                                        data: 'rm',
                                        timeout: 2000,
                                        success: function(rsp) {
                                            lastversion = rsp.lastversion;
                                            if (version < lastversion) {
                                                document.getElementById("upgrade").style.display = "block";
                                            }
                                        }
                                    });
                                }, 1000);

                            }

                        });
                    }

                    function upgrade() {
                        var index = layer.load(0, {
                            shade: [0.2, '#393D49']
                        });
                        $.getJSON('<%=luci.dispatcher.build_url("api","misstar","update")%>', {}, function(rsp) {
                            if (rsp.code == 0) {
                                parent.location.reload();
                                parent.layer.close(index);
                            } else {
                                $.alert(rsp.msg);
                                parent.layer.close(index);
                            }
                        });
                    }

                    function uninstall() {
                        var index = layer.load(0, {
                            shade: [0.2, '#393D49']
                        });
                        $.getJSON('<%=luci.dispatcher.build_url("api","misstar","uninstall")%>', {}, function(rsp) {
                            window.location.href = '../../';
                        });
                    }

                    function openLayer(val){
                        layer.open({
                                type: 2,
                                skin: 'layui-layer-rim', //加上边框
                                area: ['90%', '90%'], //宽高
                                title: val+'设置',
                                content: '<%=luci.dispatcher.build_url("web","misstar")%>'+'/'+val
                            });
                    }


                    $(function() {
                        initMT();
                    });
                </script>
        </body>

        </html>